package com.niiwoo.civet.trade.listener;

import java.io.IOException;
import java.util.Objects;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.account.service.NiiwooBillDubboService;
import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.civet.trade.dao.entity.InvestAmountUnfreeze;
import com.niiwoo.civet.trade.dto.IntelligenceUnfreezeDTO;
import com.niiwoo.civet.trade.service.local.intelligenceInvest.IntelligenceInvestService;
import com.niiwoo.civet.trade.service.local.intelligenceInvest.IntelligenceOrderService;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * 资金解冻异常处理
 * @author liuchun
 *
 * 2018年11月16日
 */
@Slf4j
@Component
public class IntelligenceUnfreezeEventListener {
	@Reference(version = "1.0.0")
	private NiiwooBillDubboService niiwooBillDubboService;
	@Autowired
	private IntelligenceOrderService intelligenceOrderService;
	
	@RabbitListener(queues = {RabbitConstant.Queue.INTELLIGENCE_INVEST_CANCEL_AMOUNT})
	public void investEventSend(Long packInvestOrderId, Message message, Channel channel) throws IOException {
		log.info("智能投解冻资金MQ接受消息{}", packInvestOrderId);
		Boolean isAck = true;
		try {
			InvestAmountUnfreeze investAmountUnfreeze=intelligenceOrderService.findUnFree(packInvestOrderId);
			if(Objects.isNull(investAmountUnfreeze)) {
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
				try {
					Thread.sleep(5 * 1000L);
				} catch (Exception expect) {
				}
				return;
			}
			if(Byte.valueOf("0").equals(investAmountUnfreeze.getStatus())) {
				niiwooBillDubboService.billIntelligenceInvestCancel(investAmountUnfreeze.getUserId(), packInvestOrderId+"");
			}
			intelligenceOrderService.unfreezeAmountsuccess(packInvestOrderId);
			log.info("智能投解冻资金成功{}", packInvestOrderId);
		}  catch (Exception e) {
			log.error("智能投解冻资金异常，request{},{}" ,packInvestOrderId, e.getMessage());
			isAck = false;
			try {
				Thread.sleep(5 * 1000L);
			} catch (Exception expect) {
			}
		} finally {
			if (isAck) {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			} else {
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
			}
		}
	}
}
